/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <los_typedef.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "JYRTC_rtc.h"
#include "wifi_connect.h"
#include "ntpUdp.h"
#include "iot_gpio.h"

#define TASK_STACK_SIZE 1024 * 8
#define TASK_PRIO 25
#define SELECT_WIFI_SSID "aaa"
#define SELECT_WIFI_PASSWORD "talkweb1996"
#define THREAD_STACK_SIZE 10240
#define NTP_ALIYUN_COM "ntp.aliyun.com"
#define NTP_SERVER_PORT 123
#define RET_OK 0
#define RET_FAIL 1

const char* NTP_SERVERS[10] = { "ntp.aliyun.com",
                                 "ntp1.aliyun.com",
                                 "ntp2.aliyun.com",
                                 "ntp3.aliyun.com",
                                 "ntp4.aliyun.com",
                                 "ntp5.aliyun.com",
                                 "ntp6.aliyun.com",
                                 "ntp7.aliyun.com",
                                 "cn.pool.ntp.org"
                              };

struct tm time_value = {0};

static void WifiConnectTask()
{
    if (WifiConnect(SELECT_WIFI_SSID, SELECT_WIFI_PASSWORD) == 0 ) 
    {
        printf("wifi connected\n");
    }

    for (int i = 0; i < 10; i++) 
    {
        if (GetTimeTm(NTP_SERVERS[i], NTP_SERVER_PORT, &time_value)) 
        {
            DS1307_SetInit(&time_value);
            rct_set_init();
            break;
        }
    }

}

static void DS1307_Task(void* argc)
{
    printf("start ds1307 task\n");
	rtc_timer(argc);
}

static void DS1307ExampleEntry(void)
{  
    osThreadAttr_t attr;
    InitGpio5Isr();
    attr.name = "1307_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;
	if (osThreadNew((osThreadFunc_t)WifiConnectTask, (void*)sem_udp, &attr) == NULL)
    {
        printf("[ntp_wifi_Demo] Falied to create wifi ntp task!\n");
    }

    if (osThreadNew((osThreadFunc_t)DS1307_Task, NULL, &attr) == NULL)
    {
        printf("Falied to create Example_Task!\n");
    }
}

APP_FEATURE_INIT(DS1307ExampleEntry);



